import ProxyGoods from "./proxyGoods";
import pub from "../common/pub";

/**
 * push方法重写
 * ShoppingCartList类为单例类
 * 相同商品相同类型合并为同一个商品
 * @author jjw
 */
class ShoppingCartList{
    constructor(list) {
        this.list = list || []
    }
}
ShoppingCartList.prototype.mergeGoods = function (goods) {
    const _index = this.list
        .findIndex(item => item.goodsId === goods.goodsId
            && item.goodsTagId === goods.goodsTagId && goods.promotionGroupKey === item.promotionGroupKey)
    if(~_index){
        const oldGoods = this.list.splice(_index,1)[0]
        goods.goodsCount = oldGoods.goodsCount + goods.goodsCount
        return goods;
    }else {
        return goods
    }
}
ShoppingCartList.prototype.push = function (items) {
    //查找当前列表是否存在同名切名称相同商品
    if (Array.isArray(items)) {
        for (let i = 0; i < items.length; i++) {
            this.list.push(this.mergeGoods(items[i]))
        }
        pub.$pub('updateGoodsData',true)
    }else {
        this.list.push(this.mergeGoods(items));
    }
}
ShoppingCartList.prototype.toList = function () {
    return this.list
}
const _cacheShoppingCart = {};
//清空购物车缓存
const removeCacheShoppingCart = function (arg){
    const _arg = arg || 'cart'
    uni.removeStorage(_arg)
    Reflect.deleteProperty(_cacheShoppingCart,_arg);
}

const proxyShoppingCartList = new Proxy(ShoppingCartList,{
    construct(target, argArray, newTarget) {
        const _arg = argArray[0] || 'cart'
        console.log("================",_arg)
        const isHas = Reflect.has(_cacheShoppingCart,_arg)
        if(isHas)return _cacheShoppingCart[_arg];
        //查询缓存中是否有数据没有就new一个新数组返回
        // const cacheList = localStorage.getItem(_arg)
        // const cacheList = uni.getStorage(_arg)

        // console.log("cacheList"+JSON.stringify(cacheList))
        // if(cacheList && cacheList !== ''){
        //     // JSON.parse(cacheList)
        //     _cacheShoppingCart[_arg]=cacheList;
        //     return _cacheShoppingCart[_arg]
        // }
        const list = new ShoppingCartList()
        _cacheShoppingCart[_arg] = list;
        return  list
    },
})
export {proxyShoppingCartList as ShoppingCartList,removeCacheShoppingCart}

//临时购物缓存对象
export 	const cartType = {
        cart:'shoppingTemporary',
        stock: 'stockTemporary',
        buy: 'buyTemporary',
        updateSale:'updateSaleTemporary',
        capCart:'capCartTemporary',
        capCartOrder:'capCartOrderTemporary',
        otherEnter:'otherEnterTemporary',
        ohterOut:'otherOutTemporary',
        buyEnter:'buyEnterTemporary',
        wareSalesReturn:'wareSalesReturnTemporary',
        wareCheck:'wareCheckTemporary',
        buyApply: 'buyApplyTemporary',
}
